package com.dxq.test.activity;

import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dxq.test.App;
import com.dxq.test.common.AppManager;
import com.dxq.test.R;
import com.dxq.test.adapter.StockAdapter;
import com.dxq.test.common.Constant;
import com.dxq.test.db.Group;
import com.dxq.test.db.Label;
import com.dxq.test.db.LabelGroup;
import com.dxq.test.db.Pasture;
import com.dxq.test.db.TablesDao;
import com.j256.ormlite.dao.ForeignCollection;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * Author: zsh
 * Date: 2023/11/15
 * Describe: 牲畜列表页面（创建修改群成员的时候使用）
 * group不为空的时候是修改群成员
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class StockActivity extends AppCompatActivity implements View.OnClickListener {

    public TablesDao tablesDao;

    private ImageView ivBack, ivMore;
    private TextView tvTitle, tvSet, tvQuery;
    private EditText etContent;
    private RecyclerView recyclerView;
    private Button btnCheckAll;

    private StockAdapter mAdapter;
    private List<Label> recordList = new ArrayList<>();

    private String groupName = "";
    private Group group = null;
    private int checkSize = 0;
    private boolean isCheckAll = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_stock);
        tablesDao = new TablesDao(this);
        groupName = getIntent().getStringExtra("groupName");
        group = (Group) getIntent().getSerializableExtra("group");
        initView();
        initAdapter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        ivMore = findViewById(R.id.ivMore);
        tvTitle = findViewById(R.id.tvTitle);
        tvSet = findViewById(R.id.tvSet);
        tvTitle.setText(groupName);
        tvSet.setVisibility(View.VISIBLE);
        tvSet.setText("确定(" + checkSize + ")");

        recyclerView = this.findViewById(R.id.recyclerView);
        btnCheckAll = this.findViewById(R.id.btnCheckAll);
        tvQuery = this.findViewById(R.id.tvQuery);
        etContent = this.findViewById(R.id.etContent);

        ivBack.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        btnCheckAll.setOnClickListener(this);
        tvQuery.setOnClickListener(this);

        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals(""))
                    getData(s.toString());
            }
        });
    }

    private void initAdapter() {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));//添加分割线
        mAdapter = new StockAdapter(R.layout.item_stock, recordList);//
        recyclerView.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.layout_empty);

        //item点击事件
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter,
                                    @NonNull @NotNull View view, int position) {
                //ToastUtils.showShort("item事件");
            }
        });

        //item子view点击事件
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter,
                                         @NonNull @NotNull View view, int position) {
                //ToastUtils.showShort("child添加事件");
                Label label = recordList.get(position);
                label.setCheck(!label.isCheck());
                refreshData();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                StockActivity.this.finish();
                break;

            case R.id.tvSet:
                if (null != group) {
                    updateGroup();
                } else {
                    createGroup();
                }
                break;

            case R.id.btnCheckAll:
                checkAll();
                break;

            case R.id.tvQuery:
                String content = etContent.getText().toString();
                if (content.equals("")) {
                    ToastUtils.showShort("请输入关键字进行查询！");
                    return;
                }
                getData(content);
                break;
        }
    }

    private void getData(String content) {
        recordList.clear();
        List<Label> labels = tablesDao.queryLabels(App.select_pasture_id, Constant.BREEDSTATUS_CUNLAN, false);
        if (null == group) {
            if (null != labels) {
                for (Label label : labels) {
                    if (likeQuery(label, content))
                        recordList.add(label);
                }
            }
        } else {
            List<Label> labelForGroup = tablesDao.queryLabelForGroup(group);
            if (null != labels) {
                for (Label label : labels) {
                    if (likeQuery(label, content)) {
                        if (checkLabelExist(labelForGroup, label)) {
                            //存在
                            label.setExist(true);
                            label.setCheck(true);
                        }
                        recordList.add(label);
                    }
                }
            }
        }

        refreshData();

    }

    //刷新列表数据
    private void refreshData() {
        checkSize = 0;
        if (null != recordList && recordList.size() > 0) {
            for (Label label : recordList) {
                if (label.isCheck()) {
                    checkSize++;
                }
            }
        }
        tvSet.setText("确定(" + checkSize + ")");
        mAdapter.notifyDataSetChanged();
    }

    //判断牲畜是否已在群内
    private boolean checkLabelExist(List<Label> list, Label label) {
        Optional<Label> first = list.stream().filter(parent ->
                parent.getID().equals(label.getID())).findFirst();
        if (first.isPresent()) {
            return true;//存在
        }
        return false;//不存在
    }

    //模糊查询
    private boolean likeQuery(Label label, String content) {
        if (content.equals("")) {
            return true;
        }
        if (label.getID().contains(content) ||
                label.getName().contains(content)) {
            return true;//存在
        }
        return false;//不存在
    }

    private void checkAll() {
        isCheckAll = !isCheckAll;
        if (null != recordList && recordList.size() > 0) {
            for (Label label : recordList) {
                if (!label.isExist())
                    label.setCheck(isCheckAll);
            }
        }
        refreshData();
    }

    //新增群操作
    private void createGroup() {
        if (checkSize == 0) {
            ToastUtils.showShort("未选择牲畜");
            return;
        }
        //判断该群名称是否已经注册
        List<Group> groups = tablesDao.queryGroupByName(groupName);
        if (null != groups && groups.size() > 0) {
            ToastUtils.showShort("该群名称已注册");
            return;
        }
        //添加数据
        insertGroupLabel();
    }

    //更新群操作
    private void updateGroup() {
        //更新数据
        updateGroupLabel();
    }

    private void insertGroupLabel() {
        String nowTime = TimeUtils.getNowString();
        //查询当前所选择牧场
        Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
        //1、首先插入一条群数据
        Group group = new Group(groupName, nowTime, nowTime, pasture);
        int i = tablesDao.insertGroup(group);
        if (i > 0) {
            //插入成功
            List<LabelGroup> labelGroupList = new ArrayList<>();
            for (Label label : recordList) {
                if (label.isCheck()) {
                    //2、生成关联数据
                    LabelGroup labelGroup = new LabelGroup(label, group);
                    labelGroupList.add(labelGroup);
                }
            }
            //3、插入关联数据
            int size = tablesDao.insertLabelGroup(labelGroupList);
            if (size == labelGroupList.size()) {
                //4、插入成功后，返回到群列表页面
                StockActivity.this.finish();
            } else {
                //插入失败
                ToastUtils.showShort("创建牲畜群关联数据失败");
            }
        } else {
            //插入失败
            ToastUtils.showShort("创建群数据失败");
        }
    }

    private void updateGroupLabel() {
        List<LabelGroup> labelGroupList = new ArrayList<>();
        for (Label label : recordList) {
            if (label.isCheck() && !label.isExist()) {
                //1、生成关联数据
                LabelGroup labelGroup = new LabelGroup(label, group);
                labelGroupList.add(labelGroup);
            }
        }
        //2、插入关联数据
        int size = tablesDao.insertLabelGroup(labelGroupList);
        if (size == labelGroupList.size()) {
            //4、插入成功后，返回到群列表页面
            StockActivity.this.finish();
        } else {
            //插入失败
            ToastUtils.showShort("创建牲畜群关联数据失败");
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}
